<!-- 封闭生产申请单 -->
<template>
  <view>
    <u--form
      labelPosition="top"
      :model="form"
      :rules="rules"
      ref="form"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基础信息</view>
        <u-form-item label="单据编号" prop="closePdtBillNo" :borderBottom="false" required>
          <u--input disabled placeholder="请输入单据编号" v-model="form.closePdtBillNo" border="surround"></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="proposerTime" :borderBottom="false" required>
          <u--input
            v-model="form.proposerTime"
            disabled
            placeholder="请选择时间"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer" :borderBottom="false" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="form.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="form.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" :borderBottom="false" required>
          <h-select-depart-input
            disabled
            v-model="form.proposerDeptId"
            :departName="form.proposerDeptIdText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="form.proposerDeptIdText"
          ></h-select-depart-input>
        </u-form-item>
      </view>
      <view class="basic-style">
        <view class="basic-title basic-border">封闭信息</view>
        <u-form-item label="项目名称" prop="projectId" required>
					<h-select-project-distribution-input
					  :projectStatus="'2'"
						:proDisabled="true"
						:isContractManager="true"
						:isProductionClose="true"
					  v-model="form.projectId"
						objectField="form.projectId"
					  style="width: 100%"
					  placeholder="请选择项目名称"
					  border="surround"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  @input="handleProjectIdChange"
					></h-select-project-distribution-input>
        </u-form-item>
        <u-form-item label="项目编号" prop="projectNo" :borderBottom="false">
          <u--input v-model="form.projectNo" disabled placeholder="请输入项目编号" border="surround"></u--input>
        </u-form-item>
				<u-form-item label="经营团队" prop="teamName" :borderBottom="false">
					<h-select-team-input
					  disabled
					  style="width: 100%"
					  v-model="form.teamName"
					  objectField="form.teamName"
					  placeholder="请选择经营团队"
					  border="surround"
					  :tdlx="1"
					/>
				</u-form-item>
        <u-form-item label="业务名称" prop="projectTaskId" :borderBottom="false" required>
					<h-select-task-file-input-popup
					  :projectId="form.projectId"
					  v-model="form.projectTaskId"
					  class="w-100"
					  :label="'categoryName'"
					  :disabled="!form.projectId"
					  placeholder="请选择业务名称"
					  searchPlaceholder="请选择业务名称"
					  border="surround"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
					  @realChange="handleTaskIdChange"
					  :customParams="{
					    distributionType: 'producting'
					  }"
					  @select="form.taskDescription = $event.data.taskDescription"
					></h-select-task-file-input-popup>
        </u-form-item>
        <u-form-item label="任务编号" prop="billNo" :borderBottom="false">
          <u--input v-model="form.billNo" disabled placeholder="请输入任务编号" border="surround"></u--input>
        </u-form-item>
        <u-form-item label="实施部门" prop="executeDepart" :borderBottom="false">
          <h-select-depart-input
            disabled
            v-model="form.executeDepart"
            :departName="form.productTeamText"
            placeholder="请选择实施部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="form.productTeamText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="生产团队" prop="productTeam">
          <h-select-team-input
						disabled
            style="width: 100%"
            v-model="form.productTeam"
            objectField="form.productTeam"
            placeholder="请选择生产团队"
            border="surround"
            :tdlx="3"
          />
        </u-form-item>
				
        <u-form-item label="项目负责人" prop="projectLeading" :borderBottom="false">
          <h-select-person-input
						isMulti
            style="width: 100%"
            disabled
            v-model="form.projectLeading"
            placeholder="请选择项目负责人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="form.projectLeading"
          ></h-select-person-input>
        </u-form-item>
				
				<u-form-item label="封闭时间" prop="closeStartDate" :borderBottom="false" required>
          <h-calendar-datetime-select
          	style="width: 100%"
          	v-model="closeDate"
          	@confirm="onCalendarConfirm"
          	placeholder="请选择封闭时间"
          ></h-calendar-datetime-select>
        </u-form-item>
				
				<u-form-item label="封闭人员" prop="closeUserNames" :borderBottom="false" required>
				  <h-select-person-input
						isMulti
				    style="width: 100%"
				    v-model="form.closeUserNames"
				    placeholder="请选择封闭人员"
				    border="surround"
				    suffixIcon="arrow-down-fill"
				    :suffixIconStyle="{ color: '#B2B2B2' }"
				    objectField="form.closeUserNames"
				  ></h-select-person-input>
				</u-form-item>
        <u-form-item label="申请原因" prop="closeApplyReason" :borderBottom="false" required>
          <u--textarea v-model="form.closeApplyReason" :maxlength="500" count :confirm-type="null" placeholder="请输入申请原因"></u--textarea>
        </u-form-item>
				<u-form-item label="预期成果" prop="expectResult" :borderBottom="false" required>
				  <u--textarea v-model="form.expectResult" :maxlength="500" count :confirm-type="null" placeholder="请输入预期成果"></u--textarea>
				</u-form-item>
        <u-form-item label="备注" prop="remark" :borderBottom="false">
          <u--textarea v-model="form.remark" :maxlength="500" count :confirm-type="null" placeholder="请输入备注"></u--textarea>
        </u-form-item>
      </view>
      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="form.attachmentFile" :isIcon="false"></h-upload-file>
          <file-list v-if="form.attachmentFile" v-model="form.attachmentFile" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
      <u-toast ref="uToast"></u-toast>
      <ProcessNodeConfiguration ref="processConfig" isAfterStart="1" isCheck="1" @ok="onOk"></ProcessNodeConfiguration>
    </u--form>
  </view>
</template>

<script>
import moment from 'moment'
import fileList from '@/pages/synergy/components/fileList.vue'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import { add, edit, info, gainBillNo } from '@/api/project/ErpProductionCloseForm.js'
import { mapState } from 'vuex'
import { queryDistributionProjectList } from '@/api/index'
// import defaultList from '@/pages/synergy/components/defaultList.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import http from '@/utils/request'
export default {
  components: {
    fileList,
    ProcessNodeConfiguration
    // defaultList,
  },
  data() {
    return {
			queryDistributionProjectList,
      form: {
        bpmBizTitle: '',
        closePdtBillNo: '',
        proposer: '',
        proposerDeptId: '',
        proposerTime: '',
				
        projectId: '',
        projectNo: '',
				projectName: '',
        teamName: '',
        projectTaskId: '',
        billNo: '',
        executeDepart: '',
        productTeam: '',
        projectLeading: '',
        closeStartDate: '',
        closeEndDate: '',
        closeUserNames: '',
        closeApplyReason: '',
        expectResult: '',
        remark: '',
      },
			closeDate: [],
      rules: {
        closePdtBillNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
        proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
        proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
        proposerTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],

        projectId: [{ required: true, message: '请选择项目名称!', trigger: ['blur', 'change'] }],
        projectTaskId: [{ required: true, message: '请选择业务名称!', trigger: ['blur', 'change'] }],
				
        closeStartDate: [{ required: true, message: '请选择封闭时间!', trigger: ['blur', 'change'] }],
        closeApplyReason: [{ required: true, message: '请输入申请原因!', trigger: ['blur', 'change'] }],
        expectResult: [{ required: true, message: '请输入预期成果!', trigger: ['blur', 'change'] }],
        closeUserNames: [{ required: true, message: '请选择封闭人员!', trigger: ['blur', 'change'] }],
      },
      initDictOptions,
      dictOptions: {},
      isSubmit: false,
      id: '', // 详情id值
      //代码生成后需手动设置流程编码
      flowCode: 'onl_erp_production_close',
      formUrl: '/closeProdution/modules/ErpProductionCloseForm',
      formUrlMobile: '/pages/synergy/ErpProductionCloseForm',
      beanName: 'erpProductionCloseServiceImpl',
			// urlStartProcess: '/api/erpmng/act/process/activiti/startMutilProcessCanBack'
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  onUnload() {
    this.$off('change')
  },
  created() {
    if (this.id) {
      this.loadData(this.id)
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initDictConfig()
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },
    // 选择关联任务
    handleTaskIdChange(task) {
      if (task) {
        // 当前projectId
        this.projectIdBack = this.form.projectId
        // 带出任务编号
				this.$set(this.form, 'billNo', task.billNo)

				// 带出实施部门
				this.$set(this.form, 'executeDepart', task.executeDepart)

				// 带出生产团队
				this.$set(this.form, 'productTeam', task.productTeam)

				// 带出项目负责人
				this.$set(this.form, 'projectLeading', task.projectLeading)

				// 带出业务编码
				this.$set(this.form, 'categoryCode', task.categoryCode)

				// 带出业务名称
				this.$set(this.form, 'categoryName', task.categoryName)
      } else {
        // 清空
        this.resetTaskFields()
        this.projectIdBack = null
      }
    },
    // 清空数据
    restProjectFields() {
      this.$set(this.form, 'projectNo', '') // 项目编号
			this.$set(this.form, 'projectName', '') // 项目名称
			this.$set(this.form, 'teamName', '') // 经营团队
    },
    resetTaskFields() {
			
			 this.$set(this.form, 'billNo', '')
			 this.$set(this.form, 'projectTaskId', '')
			 this.$set(this.form, 'executeDepart', '')
			 this.$set(this.form, 'productTeam', '')
			 this.$set(this.form, 'projectLeading', '')
			 this.$set(this.form, 'categoryCode', '')
			 this.$set(this.form, 'categoryName', '')
    },
    // 选择项目名称
    handleProjectIdChange(data) {
      let project = data
      if (data && project) {
        // 项目编号（档案编号）
        this.$set(this.form, 'projectNo', project.finalNo)
        // 项目名称
        this.$set(this.form, 'projectName', project.projectName)
        // 经营团队
				this.$set(this.form, 'teamName', project.oldTeamId ? project.oldTeamId : project.teamName)
      } else {
        // 清空所有
        this.restProjectFields()
      }
			this.resetTaskFields()
    },
    // ...mapState(['userInfo']),
    // 查询预立项申请详情
    loadData(id) {
      info({ id }).then(async (res) => {
        if (res.success) {
          this.form = { ...res.result }
					this.closeDate = [this.form.closeStartDate, this.form.closeEndDate]
        } else {
          this.$refs.uToast.show({
            message: res.message,
            type: 'error',
          })
        }
      })
    },
		// 选择预定日期
		onCalendarConfirm(val) {
			if (val && val.length) {
				if (val && val.length && val.length == 2) {
					this.$set(this.form, 'closeStartDate', val[0])
					this.$set(this.form, 'closeEndDate', val[val.length - 1])
					this.closeDate = [val[0], val[val.length - 1]]
				}
			}
		},
		
    // 约束数字输入框
    // onBlur(item, text) {
    //   if (item == undefined || item == null) {
    //     return false
    //   }
    //   var num = Number(item)
    //   if (num <= 0) {
    //     num = 0
    //   }
    //   if (num >= 99999) {
    //     num = 99999
    //   }
    //   this.form[text] = num.toFixed(1)
    // },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'FBSC', subSystemCode: '05' })
      this.form.closePdtBillNo = res.result
    },

    // 初始化新增需要的数据
    initForm() {
      this.form.proposer = this.userInfo.empId //当前登录人
      this.form.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.form.proposerTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    validateForm() {
      return this.$refs.form.validate()
    },
    async initDictConfig() {
      initDictOptions('erp_omc_project,project_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'projectId', res.result)
        }
      })
    },
    getCreateTime() {
      let proposerTime = this.form.proposerTime
      let date = proposerTime.substring(0, 10)
      return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.form,
          // details: this.formData,
        })
        if (response.success) {
          var that = this
          this.isSubmit = true
          // 获取流程列表
          if (this.form.id) {
            this.getProcessList(this.form.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
			this.$refs.processConfig.showPopup = true
			this.$refs.processConfig.formUrl = this.formUrl
			this.$refs.processConfig.formUrlMobile = this.formUrlMobile
			this.$refs.processConfig.flowCode = this.flowCode
			// this.$refs.processConfig.startProcess = this.urlStartProcess
			this.$refs.processConfig.edit(id, '', this.beanName)
    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.form,
          // details: this.formData,
        })
        if (response.success) {
          this.isSubmit = true
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home',
                })
              }
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
  }
}
</script>

<style lang="scss" scoped>
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
